<?php

define('COMMON_HELPER_ALLOWED_HTML', '<a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <br> <p> <img>');

/**
 * class common
 * provides common functions to be used
 */
class CommonHelper {
  /**
   * log debugging function
   * @param $o
   * @param null $label
   */
  public static function error_log($o, $label = NULL) {
    error_log($label . ' - ' . print_r($o, true));
  }

  /**
   * checking if giving url is valid and workable url
   */
  public static function is_available_url($url, $timeout = 30) {
    $ch = curl_init(); // get cURL handle

    // set cURL options
    $opts = array(CURLOPT_RETURNTRANSFER => true, // do not output to browser
      CURLOPT_URL => $url,            // set URL
      CURLOPT_NOBODY => true, 		  // do a HEAD request only
      CURLOPT_TIMEOUT => $timeout);   // set timeout
    curl_setopt_array($ch, $opts);

    curl_exec($ch); // do it!
    $curl_info = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $retval = ($curl_info < 400); // check if HTTP OK, http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#4xx_Client_Error
    curl_close($ch); // close handle

    return $retval;
  }

  /**
   * return time ago snippet
   * @param $timestamp
   * @return string
   */
  public static function format_time_ago($timestamp) {
    $date = format_date($timestamp, 'custom', 'M jS, Y');
    $time_ago = format_date($timestamp, 'custom', 'c');

    return '<abbr class="timeago" title="' . $time_ago . '">' . $date . '</abbr>';
  }

  /**
   * return absolute current path
   */
  public static function absolute_current_path() {
    return $GLOBALS['base_url'] . url(current_path());
  }

  /**
   * simular apple reader mode
   */
  public static function reader($url) {
    require_once('sites/all/libraries/php-readability/Readability.php');

    $html = file_get_contents($url);
    if (function_exists('tidy_parse_string')) {
      $tidy = tidy_parse_string($html, array(), 'UTF8');
      $tidy->cleanRepair();
      $html = $tidy->value;
    }

    // give it to Readability
    $readability = new Readability($html, $url);
    // print debug output?
    // useful to compare against Arc90's original JS version -
    // simply click the bookmarklet with FireBug's console window open
    $readability->debug = false;
    // convert links to footnotes?
    $readability->convertLinksToFootnotes = true;
    // process it
    $result = $readability->init();

    $json = array();
    if($result) {
      $content = $readability->getContent()->innerHTML;
      // if we've got Tidy, let's clean it up for output
      if (function_exists('tidy_parse_string')) {
        $tidy = tidy_parse_string($content, array('indent'=>true, 'show-body-only' => true), 'UTF8');
        $tidy->cleanRepair();
        $content = $tidy->value;
      }

      $content = strip_tags($content, COMMON_HELPER_ALLOWED_HTML);
      $json['title'] = strip_tags($readability->getTitle()->textContent);
      $json['body'] = $content;
    }
    else {
      $json['error'] = t("Looks like we couldn'\t find the content.");
    }

    drupal_json_output($json);
  }

  /**
   * out put SQL string for debugging
   * @param SelectQueryInterface $query
   * @return mixed|string
   */
  public static function get_query_string(SelectQueryInterface $query) {
    $string = (string) $query;
    $arguments = $query->arguments();

    if (!empty($arguments) && is_array($arguments)) {
      foreach ($arguments as $placeholder => &$value) {
        if (is_string($value)) {
          $value = "'$value'";
        }
      }

      $string = strtr($string, $arguments);
    }

    $string = str_replace('{', '', $string);
    $string = str_replace('}', '', $string);

    return $string;
  }

  /**
   * helper to output a flag link
   */
  public static function flag($entity_id) {
    global $user;

    if($user->uid) {
      return flag_create_link('like', $entity_id);
    }
    else {
      $flag_count = flag_get_counts('node', $entity_id);
      if(!empty($flag_count)) {
        $flag_count = $flag_count['like'];
      }
      else {
        $flag_count = 0;
      }

      return '<span class="flag-wrapper flag-like" data-toggle="modal" data-target="#modalLogin"><span class="flag">' . CommonHelper::crabii_icon('star-o') . '&nbsp;' . $flag_count . '</span></span>';
    }
  }

  /**
   * helper function for detecting private or public board
   */
  public static function is_private_board($term) {
    $field_privacy = field_get_items('taxonomy_term', $term, 'field_privacy');

    if($field_privacy && $field_privacy[0]['value'] == 'private') {
      return TRUE;
    }

    return FALSE;
  }

  /**
   * helper for mass update status.
   */
  public static function node_mass_update_status($nids, $status) {
    if(empty($nids)) {
      return;
    }

    db_update('node')
      ->fields(array('status' => $status))
      ->condition('nid', $nids, 'IN')
      ->execute();

    db_update('node_revision')
      ->fields(array('status' => $status))
      ->condition('nid', $nids, 'IN')
      ->execute();
  }

  /**
   * traverse through $element array and apply callback
   *
   * @param $input_form
   * @param $callback
   * @return array|bool
   */
  public static function element_children_alter(&$element, $callback) {
    $arg_list = func_get_args();
    $params = array();
    if(count($arg_list) > 2) {
      for($i = 2; $i < count($arg_list); $i++) {
        $params[] = $arg_list[$i];
      }
    }

    $visible_children = array();

    foreach (element_children($element) as $key) {
      $child = &$element[$key];

      // If the child is an array recursively search in it
      if ((is_array($child)) && (!empty($child))) {
        call_user_func_array(array('CommonHelper', 'element_children_alter'), array_merge(array(&$child, $callback), $params));
      }

      // Skip un-accessible children.
      if (isset($child['#access']) && !$child['#access']) {
        continue;
      }

      // Skip value and hidden elements, since they are not rendered.
      if (isset($child['#type']) && in_array($child['#type'], array('value', 'hidden'))) {
        continue;
      }

      call_user_func_array($callback, array_merge(array(&$child), $params));
      $visible_children[$key] = $child;
    }
    if (!empty($visible_children)) {
      return $visible_children;
    }
    else {
      return false;
    }
  }

  /**
   * Theme a Bootstrap awesome font.
   *
   * @param string $name
   *   The icon name, minus the "fa-" prefix.
   *
   * @return string
   *   The icon HTML markup.
   */
  public static function crabii_icon($name, $scale = NULL) {
    // Mimic the Icon API markup.
    $attributes = array(
      'class' => array('icon', 'fa', 'fa-' . $name),
      'aria-hidden' => 'true',
    );

    if(!empty($scale)) {
      $attributes['class'][] = $scale;
    }
    $output = '<i' . drupal_attributes($attributes) . '></i>';
    return $output;
  }

  /**
   * @param $name
   */
  public static function check_token($name) {
    if(isset($_POST["{$name}_token"]) && $_POST["{$name}_token"] == drupal_get_token($name)) {
      return TRUE;
    }
    else if(isset($_GET["{$name}_token"]) && $_GET["{$name}_token"] == drupal_get_token($name)) {
      return TRUE;
    }

    drupal_access_denied();
    drupal_exit();
  }
}
